/*
 Copyright (C) 2009 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.persist.support.schema;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.qdss.persist.Entity;
import org.qdss.persist.Field;
import org.qdss.persist.dialect.Dialect;
import org.qdss.persist.dialect.FieldType;
import org.qdss.persist.dialect.MySQL5Dialect;

/**
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
 * @since 0.1, 06/23/08
 * @version $Id: Table.java 119 2011-05-15 16:56:18Z zhaofang123@gmail.com $
 */
public class Table {

	private org.qdss.persist.Entity entity;
	private Dialect dialect;
	
	public static final boolean CREATE_FK = false;

	public Table(Entity entity, Dialect dialect) {
		this.entity = entity;
		this.dialect = dialect;
	}

	public String[] generateDDL(boolean drop, boolean createFk) {
		List<String> sqls = new ArrayList<String>();
		
		StringBuilder sql = new StringBuilder();

		String schema = entity.getPhysicalName();
		if (drop) {
			sql.append("drop table if exists ").append(dialect.quote(schema));
			sqls.add(sql.toString());
			sql.delete(0, sql.length());
			
			sql.append("create table /*!32312 if not exists*/ ").append(dialect.quote(schema)).append(" (");
		} else {
			sql.append("create table if not exists ").append(dialect.quote(schema)).append(" (");
		}
		
		String PK = "";
		List<Object[]> FKs = new ArrayList<Object[]>();
		
		Field[] fields = entity.getFields();
		for (int i = 0, j = fields.length; i < j; i++) {
			Field field = fields[i];
			String fName = field.getPhysicalName();
			
			if (field.getType() == FieldType.PRIMARY)
				PK = fName;
			
			if (field.getType() == FieldType.REFERENCE && createFk) {
				FKs.add(new Object[] {
						fName,
						field.getReferenceEntities()[0] });
			}

			String type = dialect.getColumnType(field.getType().getMask());
			int maxLen = field.getMaxLength();
			if (type.contains("%d") && maxLen > 0) {
				type = String.format(type, maxLen);
			}

			String canNull = "";  // "DEFAULT NULL";
			if (!field.isNullable()) {
				canNull = " not null";
				if (field.getType() == FieldType.TIMESTAMP)
					canNull += " default '0000-00-00 00:00:00'";
			}
			
			String ddl = String.format(COLUMN_,
					StringUtils.rightPad(dialect.quote(fName), 20),
					type + canNull);
			sql.append("\n  " + ddl);

			sql.append(',');
		}
		sql.append("\n  ").append(MessageFormat.format(PK_, dialect.quote(PK)));
		
		if (!FKs.isEmpty() && createFk) {
			sql.append(",\n");
			
			for (int i = 0; i < FKs.size(); i++) {
				Object[] FK = FKs.get(i);
				Entity e = (Entity) FK[1];
				
				sql.append("\n  ");
				sql.append(MessageFormat.format(FK_,
						StringUtils.rightPad(dialect.quote(FK[0].toString()), 20),
						dialect.quote(e.getPhysicalName()),
						dialect.quote(e.getPrimaryField().getPhysicalName())));
				
				if (i + 1 < FKs.size())
					sql.append(',');
			}
		}
		sql.append("\n)");
		if (dialect.getClass() == MySQL5Dialect.class)
			sql.append("Engine=InnoDB");  // ENGINE=INNODB, MyISAM?
		sqls.add(sql.toString());
		
		return sqls.toArray(new String[] {});
	}
	
	static final String COLUMN_ 	= "%s %s";
	static final String PK_			= "primary key  ({0})";
	static final String FK_ 		= "index        ({0}),\n  foreign key  ({0})  references {1}({2})";
}
